<template>
  <el-dialog v-model="visible" :title="title" width="480px" @close="onClose">
    <div class="form-title">基本信息</div>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="110px" label-position="right">
      <el-form-item label="商品名称：" prop="sName" required>
        <el-select v-model="form.sName" placeholder="请选择商品名称" style="width: 100%">
          <el-option v-for="item in productOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="生产批次：" prop="batch" required>
        <el-input v-model="form.batch" placeholder="请输入生产批次" />
      </el-form-item>
      <el-form-item label="保质期（天）：" prop="expiration_date" required>
        <el-input v-model="form.expiration_date" placeholder="请输入保质期" />
      </el-form-item>
      <el-form-item label="生产许可证号：" prop="production_License" required>
        <el-input v-model="form.production_License" placeholder="请输入生产许可证号" />
      </el-form-item>
      <el-form-item label="生产企业：" prop="manufacturing_Enterprises" required>
        <el-input v-model="form.manufacturing_Enterprises" placeholder="请输入生产企业" />
      </el-form-item>
      <el-form-item label="封面图：" prop="cover">
        <el-upload class="cover-uploader" action="#" :show-file-list="false" :auto-upload="false"
          :on-change="handleCoverChange" ref="uploadRef" name="file">
          <div class="cover-upload-box">
            <template v-if="form.coverUrl">
              <img :src="form.coverUrl" class="cover-img" />
            </template>
            <template v-else>
              <i class="el-icon-plus cover-plus"></i>
            </template>
          </div>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="onClose">取消</el-button>
      <el-button type="primary" @click="onSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { source, fileUpload } from '@/http/axiosHelper'
import { ElMessage } from 'element-plus'
import { ref, reactive } from 'vue'

const visible = ref(false)
const title = ref('')
const formRef = ref()
const form: any = reactive({
  "sName": "",
  "batch": "",
  "expiration_date": '',
  "production_License": "",
  "manufacturing_Enterprises": "",
  "createUserId": localStorage.getItem("id"),
  "url": "",
  coverUrl: '',
  id: undefined
})

// 改进版 - 添加持久化支持
const generateDateBasedNumber = (incrementLength: number = 4) => {
  const now = new Date();
  const datePart = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;

  // 从localStorage读取或初始化计数器
  const storageKey = `dateNumCounter_${datePart}`;
  let currentCount = localStorage.getItem(storageKey);

  // 如果localStorage中没有值，则初始化为0
  if (currentCount === null) {
    currentCount = '0';
  }

  // 转换为数字，递增，然后转回字符串
  const numericCount = parseInt(currentCount, 10) + 1;
  currentCount = numericCount.toString();

  // 保存新的计数器值
  localStorage.setItem(storageKey, currentCount);

  // 确保incrementLength是数字，然后生成递增部分
  const incrementPart = currentCount.padStart(incrementLength, '0');

  return datePart + incrementPart;
};

const mode = ref<'add' | 'edit'>('add')
const rules = {
  sName: [{ required: true, message: '请选择商品名称', trigger: 'change' }],
  batch: [{ required: true, message: '请输入生产批次', trigger: 'blur' }],
  expiration_date: [{ required: true, message: '请输入保质期', trigger: 'blur' }],
  production_License: [{ required: true, message: '请输入生产许可证号', trigger: 'blur' }],
  manufacturing_Enterprises: [{ required: true, message: '请输入生产企业', trigger: 'blur' }],
}
const productOptions = [
  '兔头（麻辣味）',
  '兔腿（小）',
  '兔腿（大）',
  '兔肉丝',
  '兔肉丁',
  '冷吃兔'
]
const uploadRef = ref()
let selectedFile: File | null = null
function open(data = null, dialogTitle = '添加') {
  title.value = dialogTitle
  visible.value = true
  mode.value = dialogTitle === '编辑' ? 'edit' : 'add'
  if (data) {
    Object.assign(form, data)
    fileUpload.get("/api/File/GetImageUrl", {
      params: {
        objectName: form.url
      }
    })
      .then(res => {
        console.log(res.data);

        form.coverUrl = res.data
      })

  } else {
    Object.assign(form, {
      "sName": "",
      "batch": generateDateBasedNumber(),
      "expiration_date": '',
      "production_License": "",
      "manufacturing_Enterprises": "",
      "createUserId": localStorage.getItem("id"),
      "url": '',
      coverUrl: '',
      id: 0
    })
  }
}
function onClose() {

  visible.value = false
}
function handleCoverChange(file: any) {
  selectedFile = file.raw,
    form.url = file.name
  form.coverUrl = URL.createObjectURL(file.raw)
}
async function uploadImageToMinio() {
  if (!selectedFile) return ''
  const formData = new FormData()
  formData.append('file', selectedFile)
  const res = await fileUpload.post('/api/File/UploadFile', formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  })
  return res.data.url
}
function onSave() {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {

      form.expiration_date = Number(form.expiration_date);
      form.createUserId = Number(form.createUserId);
      if (mode.value === 'add') {
        source.post("/api/Management/TracebackAdd", form)
          .then((res) => {
            if (res.data.code == 200) {
              ElMessage.success(res.data.msg)
              uploadImageToMinio()
              visible.value = false
              emitRefresh()
            }
            else {
              ElMessage.error(res.data.msg)
            }
          })
      } else if (mode.value === 'edit') {
        source.post("/api/Management/TracebackUpdate", form)
          .then((res) => {
            if (res.data.code == 200) {
              ElMessage.success(res.data.msg)
              uploadImageToMinio()
              visible.value = false
              emitRefresh()
            }
            else {
              ElMessage.error(res.data.msg)
            }
          })
      }
    }
  })
}

// 通知主页面刷新
const emit = defineEmits(['refresh'])
function emitRefresh() {
  emit('refresh')
}

defineExpose({ open })
</script>

<style scoped>
.form-title {
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 18px;
}

.cover-uploader {
  display: flex;
  align-items: center;
}

.cover-upload-box {
  width: 80px;
  height: 80px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background: #fafafa;
}

.cover-plus {
  font-size: 48px;
  color: #999;
}

.cover-img {
  width: 76px;
  height: 76px;
  object-fit: cover;
  border-radius: 4px;
}
</style>